/*
 * @description: 传感器数据Crud
 * @Date: 2023-03-22 15:18:53
 * @example: 
 * @params: 
 */
const express = require("express");
const db = require("../db/config");
const bodyParser = require("body-parser");
const Sensor = express.Router();

Sensor.use(bodyParser.json());
Sensor.use(express.urlencoded({ extended: true }));
Sensor.use(express.static(__dirname + '/www'));


Sensor.all("*", function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Methods", "PUT, GET, POST, DELETE, OPTIONS");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header("Access-Control-Allow-Headers", "Content-Type");
    res.header("Access-Control-Allow-Headers", "Authorization");
    next();
  });


/**
 * 传感器数据
 * @route GET /SensorList
 * @group DataSource - Ctwing传感器数据
 * @param {number} currentPage.query - 请输入currentPage
 * @param {number} pageSize.query - 请输入pageSize
 * @returns {object} 200 - An array of user info
 * @returns {Error}  default - Unexpected error
 */
Sensor.get('/SensorList',(req,res)=>{
    const currentPage = req.query.currentPage || 1 ;
    const pageSize = req.query.pageSize || 10 ;
    const offset = (currentPage - 1) * pageSize;
    const countSql = 'SELECT COUNT(*) AS total FROM DeviceInfo';
    const listSql = `SELECT * FROM DeviceInfo ORDER BY timestamp DESC LIMIT ${pageSize} OFFSET ${offset}`;
    db.query(countSql,(data)=>{
       if(data){
        const total = data[0].total;
        db.query(listSql,(data)=>{
            if(data){
                const queryParams = {
                    currentPage,
                    pageSize,
                    total
                }
                res.json({isSuccess:true,data:data,queryParams,Code:200,msg:"获取列表成功!"})
            }
        })
       }
    })
})

/**
 * 删除传感器数据
 * @route DELETE /SensorDel
 * @group DataSource - Ctwing传感器数据
 * @param {number} id.query.required - 请输入传感器数据id
 * @returns {object} 200 - An array of user info
 * @returns {Error}  default - Unexpected error
 */
Sensor.delete('/SensorDel',(req,res)=>{
    const { id } = req.body
    db.del(`DeviceInfo`,{data_id:id},(data)=>{
        if(data){
            res.json({isSuccess:true,Code:200,msg:"删除成功!"})
        }else{
            res.json({isSuccess:false,data:[],Code:-100,msg:"error"})
        }
    })
})



// 使用module.exprots导出路由对象
module.exports = Sensor;

